package com.example.demo.Shiro;

import com.example.demo.Entity.SysPermission;
import com.example.demo.Entity.SysRole;
import com.example.demo.Entity.SysUser;
import com.example.demo.Service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
   ;
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        SysUser sysUser=(SysUser)principalCollection.getPrimaryPrincipal();
        sysUser.setRoleList(sysUserService.getSysRoleList(sysUser.getId()));
        if(sysUser.getRoleList()!=null){
            for(SysRole role:sysUser.getRoleList()){
                authorizationInfo.addRole(role.getRole());
                if(role.getPermissionList()!=null){
                    for(SysPermission permission:role.getPermissionList()){
                        authorizationInfo.addStringPermission(permission.getPermission());
                    }
                }
            }
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        String username=token.getUsername();
        SysUser sysUser=sysUserService.findByUsername(username);
        if(sysUser==null){
            return null;
        }
    SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(sysUser,sysUser.getPassword(),"");
        return authenticationInfo;
    }
}
